Textcsv::App.controllers :phone_number do

  # get :index, :map => '/foo/bar' do
  #   session[:foo] = 'bar'
  #   render 'index'
  # end

  # get :sample, :map => '/sample/url', :provides => [:any, :js] do
  #   case content_type
  #     when :js then ...
  #     else ...
  # end

  # get :foo, :with => :id do
  #   "Maps to url '/foo/#{params[:id]}'"
  # end

  # get '/example' do
  #   'Hello world!'
  # end


  get '/' do
    render "phone_number/index"
  end


  get :group_name, :with => :id do
    CustGroup.find(params[:id]).name.to_s
  end

  get :data do
    @sort = "desc";
    if params[:sort]
      @sort = params[:sort]
    else
      @sort = "desc";
    end
    @group = CustGroup.first.id
    if params[:group]
      @group = params[:group]
    end
    @count = DidiCustPhone.where(cust_group_id: @group).count
    @did_cust_phones = DidiCustPhone.where(cust_group_id: @group).skip(params[:offset]).limit(params[:limit]).order_by(created_at: "#{@sort}")
    @result = {
      "total": @count,
       "rows": @did_cust_phones
    }
    @result.to_json

  end

  post :create, :provides => :js  do
    if params[:name].blank?
        "alert('用户姓名名不得为空');"

    elsif params[:number].blank?
      "alert('手机号不得为空');"
    else

      @didi_cust_phone = DidiCustPhone.new
      @didi_cust_phone.name = params[:name]
      @didi_cust_phone.number = params[:number]
      @didi_cust_phone.other = params[:intro]
      @didi_cust_phone.cust_group = CustGroup.find(params[:user_group])

      if @didi_cust_phone.save
        "afterSubmit();console.log('afterSubmit');"
      else
        "alert('保存未成功，请重试！');"
      end

    end

  end

  get :delete, :with => :id do
    if DidiCustPhone.find(params[:id]).destroy
      1.to_s
    else
      0.to_s
    end
  end

end
